<template>
  <el-card>
    <el-row :gutter="20">
      <el-col :span="5">
        <el-select
          v-model="queryForm.t.permType"
          placeholder="请选择权限类型"
          clearable
        >
          <el-option
            v-for="item in permTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="5">
        <el-input
          placeholder="权限编号"
          type="number"
          v-model="queryForm.t.permNo"
          clearable
        ></el-input>
      </el-col>
      <el-col :span="5">
        <el-input
          placeholder="权限名称"
          type="text"
          v-model="queryForm.t.permName"
          clearable
        ></el-input>
      </el-col>
      <el-col :span="5">
        <el-input
          placeholder="父级编号"
          type="number"
          v-model="queryForm.t.parentNo"
          clearable
        ></el-input>
      </el-col>
      <div style="height: 30px"></div>
      <el-col :span="5">
        <el-input
          placeholder="请求路径"
          type="text"
          v-model="queryForm.t.permUrl"
          clearable
        ></el-input>
      </el-col>
      <el-col :span="5">
        <el-select
          v-model="queryForm.t.publicFlag"
          placeholder="请选择公共标识"
          clearable
        >
          <el-option
            v-for="item in publicFlagList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="5">
        <el-input
          placeholder="图标"
          type="text"
          v-model="queryForm.t.permIcon"
          clearable
        ></el-input>
      </el-col>
      <el-button type="primary" :icon="Search" @click="initGetMenuList"
        >查询</el-button
      >
      <el-button type="primary" @click="handleDialogValue()">添加</el-button>
    </el-row>

    <el-divider border-style="dashed" />

    <el-table :data="tableData" stripe style="width: 100%; height: 100%">
      <el-table-column
        v-for="(item, index) in options"
        :prop="item.prop"
        :label="`${item.label}`"
        :key="index"
        :fixed="item.fixed"
        :width="item.width"
      >
        <template v-slot="{ row }" v-if="item.prop === 'createTime'">
          {{ $filters.filterUTCtimes(row.createTime) }}
        </template>

        <template v-slot="{ row }" v-else-if="item.prop === 'showLevel'">
          {{ getDictLabel(showLevelList, row.showLevel) }}
        </template>
        <template v-slot="{ row }" v-else-if="item.prop === 'permType'">
          {{ getDictLabel(permTypeList, row.permType) }}
        </template>
        <template v-slot="{ row }" v-else-if="item.prop === 'publicFlag'">
          {{ getDictLabel(publicFlagList, row.publicFlag) }}
        </template>

        <template #default="{ row }" v-else-if="item.prop === 'action'">
          <el-button type="primary" size="small" @click="handleDialogValue(row)"
            >修改</el-button
          >
          <el-button type="danger" size="small" @click="delPerm(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:currentPage="queryForm.num"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="queryForm.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @initMenuList="initGetMenuList"
    />
  </el-card>

  <Dialog
    v-model="dialogVisible"
    :dialogTitle="dialogTitle"
    :dialogTableVal="dialogTableVal"
    :parentMenuList="parentMenuList"
    @initMenuList="initGetMenuList"
    @initParentMenuList="initGetParentMenuList"
  />
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import { getPermPage, deletePerm } from '@/api/perm.js'
import {
  getDictLabel,
  showLevelList,
  publicFlagList,
  permTypeList
} from '@/util/dict'
import { ref } from 'vue'
import { options } from './options'
import { ElMessage, ElMessageBox } from 'element-plus'
import Dialog from './components/dialog.vue'
const queryForm = ref({
  t: {
    permNo: null,
    permName: '',
    permUrl: '',
    parentNo: null,
    permType: '',
    showLevel: '',
    permIcon: '',
    publicFlag: ''
  },
  sortList: null,
  page: 1,
  size: 10
})
const total = ref(0)
const tableData = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogTableVal = ref({})
const parentMenuList = ref([])

const list2tree = (data) => {
  let map = {}
  let tree = []
  data.forEach((node) => {
    map[node.permNo] = node
    node.children = []
  })
  // * obj -> {1001: {id: 1001, parentId: 0, name: 'AA'}, 1002: {...}}
  data.forEach((node) => {
    const parent = map[node.parentNo]
    if (parent) {
      // * 当前项有父节点
      map[node.parentNo].children.push({
        value: node.permNo,
        label: node.permName,
        children: node.children
      })
    } else {
      // * 当前项没有父节点 -> 顶层
      tree.push({
        value: node.permNo,
        label: node.permName,
        children: node.children
      })
    }
  })
  return tree
}

const initGetMenuList = async () => {
  const res = await getPermPage(queryForm.value)
  total.value = Number(res.total)
  tableData.value = res.dataList
}
initGetMenuList()

const initGetParentMenuList = async () => {
  const res = await getPermPage({
    t: {
      permType: '1'
    },
    sortList: null,
    page: 1,
    size: 1000
  })
  parentMenuList.value = list2tree(JSON.parse(JSON.stringify(res.dataList)))
}
initGetParentMenuList()

const handleSizeChange = (pageSize) => {
  queryForm.value.num = 1
  queryForm.value.size = pageSize
  initGetMenuList()
}

const handleCurrentChange = (page) => {
  queryForm.value.page = page
  initGetMenuList()
}

const isNull = (obj) => {
  if (!obj) return true
  if (JSON.stringify(obj) === '{}') return true
  if (JSON.stringify(obj) === '[]') return true
}

// 更新是否显示对话框
const handleDialogValue = (row) => {
  if (isNull(row)) {
    dialogTitle.value = '添加权限'
    dialogTableVal.value = {}
  } else {
    dialogTitle.value = '编辑权限'
    dialogTableVal.value = JSON.parse(JSON.stringify(row))
  }
  dialogVisible.value = true
}

// 删除
const delPerm = (row) => {
  ElMessageBox.confirm('确定要删除权限吗？', '确认提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await deletePerm(row.id)
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      initGetMenuList()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除失败'
      })
    })
}
</script>

<style lang="scss" scoped>
.el-col {
  margin-bottom: 16px;
}
.el-pagination {
  margin-top: 20px;
  // justify-content: center; //居中
  //float: left;居左
  float: right; //居右
}
:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #ff9800 !important; //修改默认的背景色
}
</style>
